package design;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import demo.wrapper.FatRma;

/**
 * Created by zhangyanfei on 2019/7/8.
 *
 * @author zhangyanfei
 * @date 2019/07/08
 */
public class WrapperProcessor {
    private List<AbstractWrapper> wrappers;
    private volatile boolean initialized = false;

    private synchronized void init() {
        if (initialized) {
            return;
        }
        // 后期改为Spring 来加载
        wrappers = new ArrayList<>();
        wrappers.add(new OrderInfoWrapper());
        wrappers.add(new ProductInfoWrapper());
        wrappers.add(new ProductInfoWrapper2());
        wrappers.add(new ProductInfoWrapper3());
        wrappers.add(new ProductInfoWrapper4());
        initialized = true;
    }

    public List<FatRma> processorWrapper(List<FatRma> fatRmas, Scope resultScope, CountDownLatch countDownLatch)
        throws InterruptedException {
        if (!initialized) {
            init();
        }
        for (AbstractWrapper wrapper : wrappers) {
            if (wrapper.getScope().isExtended(resultScope)) {
                new Thread(() -> {
                    wrapper.wrapper(fatRmas, resultScope);
                    countDownLatch.countDown();
                }, wrapper.getScope().toString()).start();
            }
        }
        countDownLatch.await();
        System.out.println("load complete");
        return fatRmas;
    }
}
